/*
PearReview - The peer review assistant.
Copyright (C) 2009  Dimitrij Pankratz, Anton Musichin
http://www.pearreview.com, info@pearreview.com

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

package com.pearreview.ui;

import java.awt.Color;
import java.awt.Font;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.swing.BorderFactory;
import javax.swing.JFormattedTextField;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;

public class TimeSpinner extends JSpinner {
	private static final long serialVersionUID = -8803911325839494637L;
	
	public TimeSpinner() {
		super(new SpinnerDateModel());

		setFont(new Font("Tahoma", Font.PLAIN, 12));
		
		DateFormat df = DateFormat
				.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
		
		String formatPattern = "H:mm";
		
		if(df instanceof SimpleDateFormat) {
			SimpleDateFormat sdf = (SimpleDateFormat) df;			
			formatPattern = sdf.toLocalizedPattern();
		}
		
		DateEditor editor = new JSpinner.DateEditor(this, formatPattern);
		
		JFormattedTextField tf = editor.getTextField();
		CutCopyPasteManager.getInstance().registerJTextComponent(tf);
		FadingManager.getInstance().registerComponent(tf);
		setEditor(editor);
		tf.setHorizontalAlignment(JFormattedTextField.LEFT);
		
		if (System.getProperty("os.name").equals("Mac OS X")) {
			tf.setBorder(BorderFactory.createMatteBorder(
					1, 1, 1, 1, new Color(0x828790)));
		} else {
			setBorder(BorderFactory.createMatteBorder(
							1, 1, 1, 1, new Color(0x828790)));
		}
	}
	
	public TimeSpinner(Date date) {
		this();
		setDate(date);
	}
	
	public void setDate(Date date) {
		SpinnerDateModel model = (SpinnerDateModel)this.getModel();
		model.setValue(date);
	}
	
	public Date getDate() {
		SpinnerDateModel model = (SpinnerDateModel)this.getModel();
		long millis = model.getDate().getTime();
		
		millis /= 1000L * 60L;
		millis *= 1000L * 60L;
		
		return new Date(millis);
	}
}
